package com.example.customview.silder

import android.content.Context
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

/**
 * Created by  you
 * Date: 2022/7/7
 * Time: 16:27
 */
class SearchCityModel: ViewModel() {
    val queryCity = MutableLiveData<String>()
    val currentCity = MutableLiveData<String>()
    val cityData = MutableLiveData<List<ProvinceDtoItem>>()
    var provinceList = MutableLiveData<List<ProvinceDtoItem>>()

    fun clearEdit(view: View){
        queryCity.value =""
    }


    /**
     * 初始化城市数据
     */
    fun queryCityListByLocal(context: Context, isSort: Boolean) {
        viewModelScope.launch(Dispatchers.IO) {
            val json = getJsonFile("assets_wey_city_province.json", context)
            val localProvinceDtoItems =
                JsonUtil.parseJsonToObject<MutableList<CityDto>>(json)

            val cites = mutableListOf<ProvinceDtoItem>()

            localProvinceDtoItems.forEach { cityDto ->
                cityDto.divisions.forEach {
                    val split = it.center?.split(Regex(","))
                    val item = ProvinceDtoItem("", it.id, "", it.name, split?.get(1), split?.get(0))
                    val pinYin = when (item.provinceName) {
                        "重庆市" -> "CHONGQIN"
                        "长春市" -> "CHANGCHUN"
                        "长沙市" -> "CHANGSHA"
                        "长治市" -> "CHANGZHI"
                        else -> {
                            PinYinUtils.getPinYin(item.provinceName)
                        }
                    }
                    item.letter = pinYin
                    cites.add(item)
                }
            }
            val list = if (isSort) {
                //排序
                cites.sortedBy { item -> item.letter?.substring(0, 1) }
            } else {
                cites
            }
            Log.i("TAGasd", "queryCityListByLocal: $list ")
            provinceList.postValue(list)
        }
    }
    /**
     * 读取json文件,将整个json文件作为字符串形式返回
     * @param fileName json文件名(带后缀)
     * @return json文件内容的字符串形式
     */
    private fun getJsonFile(fileName: String, context: Context): String {
        //将json数据变成字符串
        val stringBuilder = StringBuilder()
        try {
            //获取assets资源管理器
            //通过管理器打开文件并读取
            val bf = BufferedReader(
                InputStreamReader(
                    context.assets.open(fileName)
                )
            )
            var line: String?
            while (bf.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }

}